<template>
  <div v-if="proxy.isAuth(['ROOT', 'FLOW REGULATION:SELECT'])">
    <el-form inline :model="dataForm" :rules="dataRule" ref="form">
      <!-- 科室名称选择框 -->
      <el-form-item>
        <el-select v-model="dataForm.place" placeholder="科室名称" clearable style="width: 170px;">
          <el-option v-for="one in data.placeList" :label="one.place" :value="one.place"/>
        </el-select>
      </el-form-item>

      <!-- 蓝牙信标UUID输入框 -->
      <el-form-item prop="blueUuid">
        <el-input v-model="dataForm.blueUuid" placeholder="蓝牙信标UUID" maxlength="32" clearable/>
      </el-form-item>

      <!-- 查询按钮 -->
      <el-form-item>
        <el-button type="primary" @click="searchHandle()">查询</el-button>
        <el-button type="primary" :disabled="!proxy.isAuth(['ROOT', 'FLOW REGULATION: INSERT'])" @click="addHandle()">
          新增
        </el-button>
        <el-button type="danger" :disabled="!proxy.isAuth(['ROOT', 'FLOW REGULATION: DELETE'])" @click="deleteHandle()">
          批量删除
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-switch
            v-model="dataForm.mode"
            size="large"
            active-text="自动调流"
            inactive-text="手动调流"
            @before-change="changeModeHandle"
        />
      </el-form-item>
    </el-form>
    <el-table
        :data="data.datalist"
        :loading="data.loading"
        @selection-change="selectionChangeHandle"
        style="background: #f5f7fa;"
        border
    >
      <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50"
          :selectable="selectable"
      />

      <el-table-column
          type="index"
          header-align="center"
          align="center"
          width="108"
          label="年号"
      >
        <template #default="scope">
          <span>{{ (data.pageIndex - 1) * data.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column
          prop="place"
          header-align="center"
          align="center"
          min-width="250"
          label="科室名称"
      />

      <el-table-column
          prop="blueUuid"
          header-align="center"
          align="center"
          min-width="270"
          label="蓝牙信标UUID"
      />

      <el-table-column
          prop="realNum"
          header-align="center"
          align="center"
          min-width="120"
          label="实际排队人数"
      />

      <el-table-column
          prop="maxNum"
          header-align="center"
          align="center"
          min-width="120"
          label="最大排队人数"
      />

      <el-table-column
          prop="weight"
          header-align="center"
          align="center"
          label="调流权重"
      />
      <el-table-column
          header-align="center"
          width="150"
          label="操作"
      >
        <template #default="scope">
          <el-button
              type="text"
              v-if="proxy.isAuth(['ROOT', 'FLOW REGULATION: UPDATE'])"
              :disabled="scope.row.status"
              @click="updateHandle(scope.row.id)"
          >
            修改
          </el-button>

          <el-button
              type="text"
              v-if="proxy.isAuth(['ROOT', 'FLOW REGULATION: DELETE'])"
              :disabled="scope.row.salesVolume > scope.row.status"
              @click="deleteHandle(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="data.pageIndex"
        :page-size="data.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="data.totalCount"
        layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

  </div>
  <el-dialog
      :title="dialog.dataForm.id"
      v-if="proxy.isAuth(['ROOT', 'FLOW REGULATION: INSERT', 'FLOW REGULATION: UPDATE'])"
      :close-on-click-modal="false"
      v-model="dialog.visible"
      width="450px"
  >
    <el-form
        :model="dialog.dataForm"
        ref="dialogForm"
        :rules="dialog.dataRule"
        label-width="80px"
    >
      <el-form-item label="科室名称" prop="place">
        <el-input
            v-model="dialog.dataForm.place"
            placeholder="输入科室名称"
            maxlength="40"
            clearable
        />
      </el-form-item>

      <el-form-item label="蓝牙信标" prop="blueUuid">
        <el-input
            v-model="dialog.dataForm.blueUuid"
            placeholder="输入蓝牙信标UUID"
            maxlength="32"
            clearable
        />
      </el-form-item>

      <el-form-item label="排队上限">
        <el-input-number
            v-model="dialog.dataForm.maxNum"
            :min="1"
            :max="500"
            :step="10"
            step-strictly
        />
      </el-form-item>

      <el-form-item label="限流权重">
        <el-slider
            v-model="dialog.dataForm.weight"
            :step="1"
            show-stops
            :min="1"
            :max="10"
        />
      </el-form-item>

      <el-form-item label="优先级">
        <el-slider
            v-model="dialog.dataForm.priority"
            :step="1"
            show-stops
            :min="1"
            :max="10"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit">确定</el-button>
  </span>
    </template>

  </el-dialog>

</template>

<script setup lang="ts">
import {getCurrentInstance, reactive} from "vue";

const {proxy} = getCurrentInstance()
const dialog = reactive({
  visible: true,
  dataForm: {
    id: null,
    place: null,
    blueUuid: null,
    maxNum: 10,
    weight: 1,
    priority: 1
  },
  dataRule: {
    place: [
      {required: true, message: '科室名称不能为空', trigger: 'blur'},
      {min: 2, message: '科室名称不能少于2个字符', trigger: 'blur'},
      {pattern: /^[a-zA-Z0-9\u4e00-\u9fa5\(\)]{2,40}$/, message: '科室名称格式错误', trigger: 'blur'}
    ],
    blueUuid: [
      {required: true, message: '蓝牙信标UUID不能为空', trigger: 'blur'},
      {pattern: /^[a-zA-Z0-9]{32}$/, message: '蓝牙信标UUID格式错误', trigger: 'blur'}
    ]
  },
});

const dataForm = reactive({
  place: null,
  blueUuid: null,
  mode: null
});

const data = reactive({
  placeList: [],
  datalist: [],
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  loading: false,
  selections: []
});
const dataRule = reactive({
  blueUuid: {
    required: false,
    pattern: /^[A-Fa-f0-9]{32}$/,  // Correct regex for 32 characters of alphanumeric (A-F, a-f, 0-9)
    message: "蓝牙信标UUID格式错误"
  }
});

function loadPlaceList() {
  proxy.$http("/mis/flow_regulation/searchPlaceList", "GET", null, true, function (resp) {
    data.placeList = resp.result;
  });
}

function loadMode() {
  proxy.$http('/mis/flow_regulation/searchMode', 'GET', null, true, function (resp) {
    let result = resp.result;
    dataForm.mode = result;
  })
}

function loadDatalist() {
  data.loading = true;  // 设置loading为true，表示数据正在加载

  let json = {
    page: data.pageIndex,        // 当前页码
    length: data.pageSize,       // 每页大小
    place: dataForm.place,       // 科室名称
    blueUuid: dataForm.blueUuid // 蓝色UUID
  };

  proxy.$http('/mis/flow_regulation/searchByPage', 'POST', json, true, function (resp) {
    let page = resp.page;       // 获取分页数据
    let list = page.list;       // 获取列表数据
    console.log('list', list)
    data.datalist = list;       // 更新datalist
    data.totalCount = page.totalCount; // 更新总数据量
    data.loading = false;       // 设置loading为false，表示数据加载完成
  });
}

function searchHandle() {
  proxy.$refs['form'].validate(valid => {
    if (valid) {
      proxy.$refs['form'].clearValidate();  // 清除表单验证

      if (dataForm.place) {
        dataForm.place = null;  // 如果 place 有值，则清空
      }

      if (dataForm.blueUuid === '') {
        dataForm.blueUuid = null;  // 如果 blueUuid 是空字符串，则设置为 null
      }

      loadDatalist();  // 加载数据列表
    } else {
      return false;  // 如果表单验证不通过，返回 false
    }
  });
}

function sizeChangeHandle(val) {
  data.pageSize = val;   // 设置新的页面大小
  data.pageIndex = 1;     // 重置页码为 1
  loadDatalist();         // 加载数据列表
}

function currentChangeHandle(val) {
  data.pageIndex = val;  // 设置新的页码
  loadDatalist();         // 加载数据列表
}

function addHandle() {
  dialog.dataForm.id = null;
  dialog.dataForm.place = null;
  dialog.dataForm.blueUuid = null;
  dialog.dataForm.maxNum = 10;
  dialog.dataForm.weight = 1;
  dialog.dataForm.priority = 1;  // 修复了拼写错误，这里需要使用 = 赋值

  dialog.visible = true;  // 显示对话框

  proxy.$nextTick(() => {
    proxy.$refs['dialogForm'].resetFields();  // 重置表单字段
  });
}

function dataFormSubmit() {
  proxy.$refs['dialogForm'].validate(valid => {
    if (valid) {
      let json = {
        id: dialog.dataForm.id,
        place: dialog.dataForm.place,
        blueUuid: dialog.dataForm.blueUuid,
        maxNum: dialog.dataForm.maxNum,
        weight: dialog.dataForm.weight,
        priority: dialog.dataForm.priority
      };

      proxy.$http(`/mis/flow_regulation/${dialog.dataForm.id === null ? 'insert' : 'update'}`, 'POST', json, true, function (resp) {
        if (resp.rows === 1) {
          proxy.$message({
            message: "操作成功",
            type: "success",
            duration: 1200,
            onclose: () => {
              dialog.visible = false;
              loadDatalist();
              loadPlaceList();
            }
          });
          dialog.visible = false; // 可选
        } else {
          proxy.$message({
            message: "操作失败",
            type: "error",
            duration: 1200
          });
        }
      });
    }
  });
}

function updateHandle(id: number) {
  dialog.dataForm.id = id;  // 设置id
  dialog.visible = true;  // 显示对话框

  proxy.$nextTick(() => {
    proxy.$refs['dialogForm'].resetFields();  // 重置表单字段

    // 构造要发送的JSON对象
    let json = {id: id};

    // 发送HTTP请求
    proxy.$http('/mis/flow_regulation/searchById', 'POST', json, true, function (resp) {
      let result = resp.result;

      // 将返回的结果填充到表单中
      dialog.dataForm.place = result.place;
      dialog.dataForm.blueUuid = result.blueUuid;
      dialog.dataForm.maxNum = result.maxNum;
      dialog.dataForm.weight = result.weight;
      dialog.dataForm.priority = result.priority;
    });
  });
}

function changeModeHandle() {
  let json = {mode: !dataForm.mode};  // Corrected variable assignment
  let flag = false;

  proxy.$http('/mis/flow_regulation/updateMode', 'POST', json, function (resp) {
    if (resp.result) {
      proxy.$message({
        message: '切换成功',  // Assuming this means 'Switch successful' in Chinese
        type: 'success',  // Assuming success type for message
        duration: 800
      });
      flag = true;
    } else {
      proxy.$message({
        message: '切换失败',  // Assuming this means 'Switch failed' in Chinese
        type: 'warning',
        duration: 800
      });
      flag = false;
    }
  });
}

function selectionChangeHandle(val) {
  data.selections = val;
}

function selectable(row, index) {
  return true;
}

function deleteHandle(id) {
  // Check if an ID is provided, otherwise use selected data
  let ids = id ? [id] : data.selections.map(item => item.id);

  // If no IDs are selected, show a warning message
  if (ids.length === 0) {
    proxy.$message({
      message: '没有选择要删除的记录', // "No records selected for deletion"
      type: "warning",
      duration: 1200
    });
  } else {
    // Confirm deletion with a dialog
    proxy.$confirm('确定要删除选中的记录?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      let json = {ids: ids};

      proxy.$http('/mis/flow_regulation/deleteByIds', 'post', json, true, function (resp) {
        if (resp.rows > 0) {
          proxy.$message({
            message: '删除成功',
            type: 'success',
            duration: 1200,
            onClose: () => {
              loadDatalist();
              loadPlaceList();
            }
          });
        } else {
          proxy.$message({
            message: '删除失败',
            type: 'error',
            duration: 1200
          });
        }
      });
    }).catch(() => {
      proxy.$message({
        message: '删除操作已取消',
        type: 'info',
        duration: 1200
      });
    });
  }
}


loadDatalist();
loadPlaceList();
loadMode();
</script>

<style scoped lang="less">
@import "flow_regulation";


</style>
